package com.example.baron;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;



public class TimerFragment2 extends Fragment implements View.OnClickListener {
	static View v;
	boolean isRun = false;
	long startTime = 0;
	Handler tickHandler = new Handler();
	TextView clockTV2;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
			Bundle savedInstanceState) {

		/*
		 * try{ v = inflater.inflate(R.layout.fragment, viewGroup,false);
		 * }catch(InflateException e){}
		 */

		LinearLayout rootView = (LinearLayout) inflater.inflate(
				R.layout.frgment2, viewGroup, false);
		rootView.setOnClickListener(this);
		clockTV2 = (TextView) rootView.findViewById(R.id.clockTV2);

		return rootView;
	}

	@Override
	public void onClick(View view) {
		toggle();
	}

	/*
	 * @Override public void onDestroyView() { super.onDestroyView(); if(v !=
	 * null){ ViewGroup parent = (ViewGroup) v.getParent(); if(parent!=null){
	 * parent.removeView(v); } }
	 * 
	 * }
	 */

	void toggle() {
		isRun = !isRun;
		if (isRun) {
			startTime = SystemClock.uptimeMillis();
			tickHandler.postDelayed(tickThread, 0);
			toast("START");

		} else {
			tickHandler.removeCallbacks(tickThread);
		}
	}

	void toast(String message) {
		Toast.makeText(getView().getContext(), message, Toast.LENGTH_SHORT)
				.show();
	}

	Runnable tickThread = new Runnable() {

		@Override
		public void run() {
			long diff = SystemClock.uptimeMillis() - startTime;
			int seconds = (int) (diff / 1000);

			int minutes = (seconds / 60);
			seconds %= 60;

			int hours = (minutes / 60);
			minutes %= 60;

			int milliseconds = (int) (diff % 1000);
			clockTV2.setText(String.format("%02d:%02d:%02d.%03d", hours,
					minutes, seconds, milliseconds));
			tickHandler.postDelayed(tickThread, 0);
		}
	};

}
